<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\general\LihuaCity;
use app\common\model\goods\LihuaGoods;
use app\common\model\LihuaUseraddr;

/**
 * 购物车
 */
class Cart extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 购物车主页
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="city_id", type="int", required=true, description="城市ID")
     * @ApiParams   (name="store_id", type="int", required=true, description="门店ID")
     * @ApiParams   (name="goods_nums", type="string", required=true, description="商品ID及数量键值对JSON字符串")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1573029605","data":{"goods":[{"id":43,"category_id":57,"name":"蛋花汤料","short_name":"蛋花汤","description":"含汤碗 净含量8克（配餐产品，不单独售卖）","pic":"http://image.lihua.com/images/newweb/2016/09/thumb_57cfc743835e0.jpg","price":2,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":0,"enable_stock":0,"num":3,"num_price":6},{"id":44,"category_id":57,"name":"三件套","short_name":"三件套","description":"三件套（不含汤勺，配餐产品，不单独售卖）","pic":"http://image.lihua.com/images/newweb/2018/12/thumb_5c0f521445dd8.JPG","price":2.5,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":0,"enable_stock":0,"num":1,"num_price":2.5}],"goods_nums":{"43":3,"44":1},"goods_stocks":null,"goods_amount":8.5,"packing_fee":0,"enough_fee":0,"subtotal":8.5,"discount":0,"submit":0,"error":"请选择一份主食，配餐商品单点不送"}})
     */
    public function index()
    {
        $this->request->filter('trim,strip_tags');
        $city_id    = (int)$this->request->post('city_id', 0);
        $store_id   = (int)$this->request->post('store_id', 0);
        if (!$city_id || !$store_id) $this->error('非法操作');

        $city = LihuaCity::getCityInfo($city_id);
        if (!$city) $this->error('非法操作');

        $goods_nums = $this->request->post('goods_nums', '');
        if ($goods_nums) {
            $goods_nums = json_decode($goods_nums, true);
            if (json_last_error()) $this->error('非法操作');
        } else {
            $goods_nums = [];
        }

        $data = LihuaGoods::getCartGoodsList($store_id, $goods_nums);
        //城市满减
        $enough = LihuaCity::countEnough($city['enough'], $data['goods_amount']);

        $discount = $enough['reduce'];//已优惠
        $subtotal = round($data['goods_amount'] - $discount, 2);//小计
        $data['enough_fee'] = $enough['reduce'];
        $data['subtotal']   = $subtotal;
        $data['discount']   = $discount;

        //结算
        if (!$data['alone_sale']) {
            $submit = 0;
            $error  = '请选择一份主食，配餐商品单点不送';
        }
        elseif ($data['lack_goods']['ids']) {
            $submit = 0;
            $error  = join('、', $data['lack_goods']['names']) . ' 库存不足';
        }
        elseif ($data['goods_amount'] < $city['min_price']) {
            $submit = 0;
            $error  = '商品起送价￥' . $city['min_price'];
        }
        else {
            $submit = 1;//为1可提交结算
            $error  = '';
        }

        $data['submit'] = $submit;
        $data['error']  = $error;

        unset($data['alone_sale'], $data['lack_goods']);
        $this->success('OK', $data);
    }

    /**
     * 商品结算
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求Token，游客不传")
     * @ApiParams   (name="city_id", type="int", required=true, description="城市ID")
     * @ApiParams   (name="store_id", type="int", required=true, description="门店ID")
     * @ApiParams   (name="goods_nums", type="string", required=true, description="商品ID及数量键值对JSON字符串")
     * @ApiParams   (name="platform", type="string", required=true, description="平台，默认为app")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1573029992","data":{"useraddr":{"id":373694,"consignee":"吴大帝","mobile":"13961259811","address":"中吴大道777号308","name":"金龙大厦","house_num":"15幢37号"},"goods":[{"id":1180,"category_id":1,"name":"冬菇滑鸡饭","short_name":"冬菇滑鸡饭","description":"冬菇滑鸡 蒜泥毛白菜 五仁酱丁萝卜干送冰红茶（图片仅供参考）","pic":"https://lihua.czapi.cn/uploads/goods/2019/10/20725d9efea561b3e.jpg","price":0.01,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":1,"enable_stock":1,"num":2,"num_price":0.02},{"id":10015,"category_id":218,"name":"特别的爱砂锅","short_name":"特爱砂锅","description":"六荤六素全家福","pic":"http://image.lihua.com/images/newweb/2019/08/thumb_5d5b494cbe158.jpg","price":25,"box_fee":1,"limit_num":1,"at_least":1,"is_alone_sale":1,"enable_stock":1,"num":1,"num_price":25}],"goods_nums":{"1180":2,"10015":1},"goods_stocks":{"1180":5000,"10015":1000},"goods_amount":25.02,"packing_fee":1,"deliver_fee":3,"enough_fee":0,"original_amount":29.02,"order_amount":29.02,"discount":0}})
     */
    public function settle()
    {
        $this->request->filter('trim,strip_tags');
        $city_id    = (int)$this->request->post('city_id', 0);
        $store_id   = (int)$this->request->post('store_id', 0);
        $goods_nums = $this->request->post('goods_nums', '');
        $platform   = strtolower($this->request->post('platform', 'app'));

        if (!in_array($platform, ['app', 'xcx'])) $this->error('非法操作');
        if (!$city_id || !$store_id) $this->error('非法操作');
        if (!$goods_nums) $this->error('请选择商品');
        $goods_nums = json_decode($goods_nums, true);
        if (json_last_error()) $this->error('非法操作');

        $data = [];

        //收货地址
        $data['useraddr'] = LihuaUseraddr::where(['user_id' => (int)$this->auth->id, 'store_id' => $store_id])
            ->field('id,consignee,mobile,address,name,house_num')->find();

        //商品列表
        $goods = LihuaGoods::getCartGoodsList($store_id, $goods_nums);
        if (!$goods['alone_sale']) $this->error('请选择一份主食，配餐商品单点不送');
        if ($goods['lack_goods']['ids']) $this->error(join('、', $goods['lack_goods']['names']) . ' 库存不足');

        $data = array_merge($data, $goods);

        //城市信息
        $city = LihuaCity::getCityInfo($city_id);
        if (!$city) $this->error('非法操作');
        if ($goods['goods_amount'] < $city['min_price']) $this->error('商品起送价￥' . $city['min_price']);
        $data['deliver_fee'] = round($city['deliver_fee'], 2);

        //城市满减
        $enough = LihuaCity::countEnough($city['enough'], $goods['goods_amount']);
        $data['enough_fee'] = $enough['reduce'];

        //订单金额
        $discount = abs($data['enough_fee']);
        $original_amount = round($goods['goods_amount'] + $data['packing_fee'] + $data['deliver_fee'], 2);
        $data['original_amount'] = $original_amount;
        $data['order_amount']    = round($original_amount - $discount, 2);
        $data['discount']        = $discount;

        unset($data['alone_sale'], $data['lack_goods']);
        $this->success('OK', $data);
    }

}
